#include "common.h"


#define NODE_CNT 80
__root __no_init volatile rtc_log_t rtc_node[NODE_CNT] @0x1000;   

//__root __no_init volatile keymap_t BIGMAP @0xE000;

__root __no_init volatile SKY_t sky @0xF600;

void FORMAT()
{
    if (sky.IsNewDisk != 0xAA)
    {
        printf("first format disk\r\n");
        
        Delayms(3000);
        printf("format => ok\r\n");
        FLASH_EraseByte((uint32_t)&sky.IsNewDisk);
        FLASH_WaitForLastOperation(FLASH_MemType_Program);
        FLASH_ProgramByte((uint32_t)&sky.IsNewDisk, 0xAA);
        FLASH_WaitForLastOperation(FLASH_MemType_Program);
    }
}

static uint8_t create_space()
{
    //uint32_t pADDR = (uint32_t)(0xCC00 + sky.current_off * 4);
    uint8_t ret = sky.current_off;
    uint8_t TMPADDR = sky.current_off + 1;
    printf("%d  %d\r\n", TMPADDR, sky.current_off);
    
    if (TMPADDR == NODE_CNT)
    {
        TMPADDR = 0;
        sky.current_off = 0;
        ret = 0;
    }
    
    //FLASH_Unlock(FLASH_MemType_Program);
    FLASH_EraseByte((uint32_t)&sky.current_off);
    FLASH_WaitForLastOperation(FLASH_MemType_Program);
    FLASH_ProgramByte((uint32_t)&sky.current_off, TMPADDR);
    FLASH_WaitForLastOperation(FLASH_MemType_Program);
    //FLASH_Lock(FLASH_MemType_Program);
    return ret;
}
 

static void memcpy_data_area(uint8_t *dst, uint8_t *src, int len)
{       
    uint32_t index = 0;

    for (index=0; index<len; index ++)
    {
        FLASH_EraseByte((uint32_t)dst);
        FLASH_WaitForLastOperation(FLASH_MemType_Data);

        FLASH_ProgramByte((uint32_t)dst++, *src++);
        FLASH_WaitForLastOperation(FLASH_MemType_Data);    
    }
}

void create_rtc_space(uint8_t *src, int len)
{
    uint8_t num = create_space();
    printf("create rtc space=%d\r\n", num);
    memcpy_data_area((uint8_t *)&rtc_node[num], src, len);
}

void save_data(uint8_t *addr, uint8_t *data, uint8_t size_data)
{
    for (int index=0; index<size_data; index ++)
    {
        FLASH_EraseByte((uint32_t)addr);
        FLASH_WaitForLastOperation(FLASH_MemType_Data);

        FLASH_ProgramByte((uint32_t)addr++, *data++);
        FLASH_WaitForLastOperation(FLASH_MemType_Data);    
    }  
}



void read_node(int number)
{
    //printf("%d-%d-%,%d-%d-%d\r\n", enode[number].time[0]);
}

void runflash_init()
{
    FLASH_Unlock(FLASH_MemType_Program);
    FLASH_Unlock(FLASH_MemType_Data);
    FORMAT();
}

